package com.arch.dev.server;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;

import com.arch.dev.client.security.AuthService;
import com.arch.dev.server.servlet.ExcelServiceServlet;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;


@SuppressWarnings("serial")
public class AuthServiceImpl extends RemoteServiceServlet implements AuthService {

	Logger logger = Logger.getLogger(AuthServiceImpl.class);
	
	@Override
	public String retrieveUsername() {
		
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		
		if (authentication==null){
			logger.info("Not logged in");
			return null;
		}
		else {
			return ((User) authentication.getPrincipal()).getUsername();
		}
		
	}

	@Override
	public String retrieveUserAuthority() {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		String auth = "";
		if (authentication==null){
			logger.info("Not logged in");
			return null;
		}
		else {
			Collection<GrantedAuthority> authorities =  ((User) authentication.getPrincipal()).getAuthorities();
		
			for (GrantedAuthority grantedAuthority : authorities) {
				
				auth = grantedAuthority.getAuthority();
			}
		}		
		return auth;
	}
	
}
